package com.bjsdzk.collector.platform.coap;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.bjsdzk.backend.rpc.OnetService;
import com.bjsdzk.backend.rpc.OpenPlatformService;
import com.bjsdzk.collector.core.Result;
import com.bjsdzk.collector.core.ResultGenerator;
import com.bjsdzk.collector.entity.xiyu.Service;
import com.bjsdzk.collector.entity.xiyu.XiyuFault;
import com.bjsdzk.collector.entity.xiyu.XiyuStatusChange;
import com.bjsdzk.collector.platform.coap.utils.JsonUtil;
import com.bjsdzk.collector.utils.TimeUtil;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.huawei.iotplatform.client.dto.*;

@RestController
@RequestMapping("/telecom-receive")
public class ReceiveController {
	
	private static Logger logger = LoggerFactory.getLogger(ReceiveController.class);
	@Autowired
    private MongoTemplate mongoTemplate;
    @Reference( check = false,version ="1.0.0")
    private OpenPlatformService openPlatformService;
    
    @PostMapping("/deviceAdd")
    public Result recvDeviceAdd(@RequestBody XiyuFault message){
    	//{notifyType=deviceAdded, deviceId=3d270392-33f0-49d8-b1c7-acb2481b1ef6, gatewayId=3d270392-33f0-49d8-b1c7-acb2481b1ef6, nodeType=GATEWAY, deviceInfo={nodeId=2222222222222222, name=null, description=null, manufacturerId=0003, manufacturerName=XIYU, mac=null, location=null, deviceType=AFD, model=XYF32i3, swVersion=null, fwVersion=null, hwVersion=null, protocolType=CoAP, bridgeId=null, status=OFFLINE, statusDetail=NOT_ACTIVE, mute=null, supportedSecurity=null, isSecurity=null, signalStrength=null, sigVersion=null, serialNumber=null, batteryLevel=null}}
    	logger.debug("deviceAdd callback"+message);
        return ResultGenerator.genSuccessResult(message);
    }

    @PostMapping("/updateDeviceInfo")
    public Result updateDeviceInfo(@RequestBody XiyuStatusChange message){
    	//logger.debug("updateDeviceInfo callback "+message);
    	//{notifyType=deviceInfoChanged, deviceId=ba13dcf2-d861-4d55-bbd9-d00aa731a20a, gatewayId=ba13dcf2-d861-4d55-bbd9-d00aa731a20a, deviceInfo={nodeId=null, name=null, description=null, manufacturerId=null, manufacturerName=null, mac=null, location=null, deviceType=null, model=null, swVersion=null, fwVersion=null, hwVersion=null, protocolType=null, bridgeId=null, status=ONLINE, statusDetail=NONE, mute=null, supportedSecurity=null, isSecurity=null, signalStrength=null, sigVersion=null, serialNumber=null, batteryLevel=null}}
    	//{notifyType=deviceInfoChanged, deviceId=23da840b-b483-4114-883b-95110ef41c9a, gatewayId=23da840b-b483-4114-883b-95110ef41c9a, deviceInfo={nodeId=868744037806019, name=null, description=null, manufacturerId=0003, manufacturerName=XIYU, mac=null, location=null, deviceType=AFD, model=XYF32i3, swVersion=null, fwVersion=null, hwVersion=null, protocolType=CoAP, bridgeId=null, status=null, statusDetail=null, mute=null, supportedSecurity=null, isSecurity=null, signalStrength=null, sigVersion=null, serialNumber=null, batteryLevel=null}}
		DeviceInfo deviceinfo = message.getDeviceInfo();
		if (deviceinfo.getStatus() != null) {
			JSONObject json = new JSONObject();
			json.put("deviceId", message.getDeviceId());
			json.put("status", deviceinfo.getStatus());
			json.put("type", 0);
			json.put("biz", 1);
			openPlatformService.changeState(json.toString());
			//biz = 1 的时候，是设备的上线下线变化，biz = 2的时候是设备的消音/复位变化
			logger.debug("updateDeviceInfo callback "+message.getDeviceId()+deviceinfo.getStatus() );
		}
        return ResultGenerator.genSuccessResult(message);
    }
    

    @PostMapping("/updateDeviceData")
	public Result updateDeviceData(@RequestBody XiyuFault message) {
    	logger.debug("updateDeviceData callback" + message);
    	//callback{notifyType=deviceDataChanged, deviceId=ba13dcf2-d861-4d55-bbd9-d00aa731a20a, gatewayId=ba13dcf2-d861-4d55-bbd9-d00aa731a20a, requestId=null, service={serviceId=detectorStatus, serviceType=detectorStatus, data={detectorAddress=1, detectorType=4, commandType=2, status=0, checkSum=7}, eventTime=20190315T034244Z}}
    	//        {serviceType=detectorReset, commandType=4, notifyType=deviceDataChanged, detectorType=4, eventTime=20190327T060520Z, checkSum=9, detectorAddress=1, serviceId=detectorReset, deviceId=23da840b-b483-4114-883b-95110ef41c9a, gatewayId=23da840b-b483-4114-883b-95110ef41c9a, createAt=2019-03-27 14:05:19}   
    	Service service = message.getService();
		ObjectNode node = service.getData();
		node.put("deviceId", message.getDeviceId());
		node.put("notifyType", message.getNotifyType());
		node.put("gatewayId", message.getGatewayId());
		node.put("serviceId", service.getServiceId());
		node.put("serviceType", service.getServiceType());
		node.put("eventTime", service.getEventTime());
		node.put("createAt", TimeUtil.getCurrentDatetime());
		if(!StringUtils.equals(service.getServiceType(), "detectorStatus")) {
			JSONObject json = new JSONObject();
			json.put("deviceId", message.getDeviceId());
			json.put("detectorAddress", node.get("detectorAddress").asText());
			json.put("operation", service.getServiceType());
			json.put("eventTime", service.getEventTime());
			json.put("type", 0);
			json.put("biz", 2);
			
			logger.debug("updateDeviceData callback restormiut" + json.toString());
			openPlatformService.changeState(json.toString());
			return ResultGenerator.genSuccessResult(message); 
		}
		JSONObject data = new JSONObject();
		Iterator<Entry<String, JsonNode>> fields = node.fields();
		while (fields.hasNext()) {
			Entry<String, JsonNode> next = fields.next();
			data.put(next.getKey(), next.getValue().asText());
		}
		if(data.get("status")!=null&&!StringUtils.equals(data.getString("status"), "0")) {
			logger.debug("updateDeviceData callback error" + data);
			mongoTemplate.save(data, "xiYuFault");
			openPlatformService.error(data.toString());
		}
		return ResultGenerator.genSuccessResult(message);
	}

    @PostMapping("/deletedDevice")
    @SuppressWarnings("unchecked")
    public Result deletedDevice(@RequestBody Object message){
    	logger.debug("deletedDevice callback"+message);
        Map<String,String> data = new HashMap<>();
        data = JsonUtil.jsonString2SimpleObj(message.toString(), data.getClass());
        //mongoTemplate.save(data, "xiYuFault");
        return ResultGenerator.genSuccessResult(data);
    }
    
    
    
}
